﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Script.Serialization;
using System.Web.Security;
using DHQGHN.PM2.Security;

namespace DHQGHN.PM2
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            //ModelBinders.Binders.Add(typeof(DHQGHN.PM2.Models.EnumeratorModel), new DHQGHN.PM2.Models.EnumeratorCustomModelBinder());
            //EncryptWebConfig();
            //log4net.Config.XmlConfigurator.Configure();
            log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(Server.MapPath("~/Web.config")));
        }

        //phunx1, 20150605: ham luu thong tin user vao cookie va mapping thong tin chung User voi HttpContext.User
        protected void Application_PostAuthenticateRequest(object sender, System.EventArgs e)
        {
            try
            {
                HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];


                if (authCookie != null)
                {
                    FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

                    var serializer = new JavaScriptSerializer();

                    var serializeModel = serializer.Deserialize<MyPrincipalSerializeModel>(authTicket.UserData);

                    var newUser = new MyPrincipal(authTicket.Name);
                    if (serializeModel != null) { 
                    newUser.UserName = serializeModel.UserName;
                    newUser.AdminID = serializeModel.AdminID;
                    newUser.AdminCode = serializeModel.AdminCode;
                    newUser.AdminName = serializeModel.AdminName;
                    newUser.FullName = serializeModel.FullName;
                    //phunx1, 20150702: lay them truong GroupCode tu bang Enumerator
                    //newUser.GroupCode = serializeModel.GroupCode;
                    //Quang 20150729: lay them truong Roles tu bang Enumerator
                    //newUser.Roles = serializeModel.Roles;
                    newUser.CountDay = serializeModel.CountDay;

                    HttpContext.Current.User = newUser;
                    }
                }
            }
            catch (HttpException ex)
            {
                throw ex;
            }
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            var error = Server.GetLastError();
            var cryptoEx = error as CryptographicException;
            if (cryptoEx != null)
            {
                //FederatedAuthentication.WSFederationAuthenticationModule.SignOut();
                Server.ClearError();
            }
        }

        private void EncryptWebConfig()
        {
            try
            {
                Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
                ConfigurationSection section = config.GetSection("connectionStrings");
                if (!section.SectionInformation.IsProtected)
                {
                    section.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider");
                    config.Save();
                }
            }
            catch (Exception ex)
            { }
        }

        private void DecryptWebConfig()
        {
            try
            {
                Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
                ConfigurationSection section = config.GetSection("connectionStrings");
                if (section.SectionInformation.IsProtected)
                {
                    section.SectionInformation.UnprotectSection();
                    config.Save();
                }
            }
            catch (Exception ex)
            { }

        }
        
        //protected void Session_Start()
        //{
        //    Session.Timeout = 20;
        //}

    }
}
